package com.ffalcon.mercury.android.sdk.demo.api;


import android.content.Context;

import com.ffalcon.mercury.android.sdk.demo.MercuryDemoApplication;
import com.ffalcon.mercury.android.sdk.demo.SPUtils;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitManager {
    public static String DEFAULT_BASE_URL = "";

    // 封装 OkHttpClient 配置
    private static OkHttpClient getOkHttpClient() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        return new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .build();
    }

    // 根据 baseUrl 创建 Retrofit 实例
    private static Retrofit createRetrofit(String baseUrl) {
        return new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(getOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .build();
    }

    // 获取默认 baseUrl 的 ApiService 实例
    public static ApiService getApiService() {

        // 在 Java 类中获取 Kotlin 实现的全局上下文
// 在 Java 类中获取 Kotlin 实现的全局上下文
        Context context = MercuryDemoApplication.getContext();


// RetrofitManager.java 中修正调用方式
        String savedUrl = (String) SPUtils.INSTANCE.getValue(context, "ipLocation", "");
        // 赋值给默认 BaseUrl（确保不为 null）
        DEFAULT_BASE_URL = savedUrl != null ? savedUrl : "";

        return getApiService(DEFAULT_BASE_URL);
    }

    // 获取指定 baseUrl 的 ApiService 实例
    public static ApiService getApiService(String baseUrl) {
        Retrofit retrofit = createRetrofit(baseUrl);
        return retrofit.create(ApiService.class);
    }
}